# coding=utf-8

import misc
from base import sg

from mgr.timer_mgr import TimerMgr

class User():
	def __init__(self):
		self.id = None
		self.dUserInfo = {}

@sg.singleton
class UserMgr(sg.SingletonBase["UserMgr"]):
	def __init__(self):
		self.user_dict: [int, User] = {}
		self.heart_set = set()
		TimerMgr.ins.add_timer(self, "loop", 15, True)
	
	async def loop(self):
		await self.check_heart()
	
	async def add_user(self, dUserInfo: dict):
		user = User()
		user.id = dUserInfo["id"]
		user.dUserInfo = dUserInfo
		
		self.heart_set.add(user.id)
		self.user_dict[user.id] = user
	
	async def remove_user(self, user_id):
		self.user_dict.pop(user_id, None)
	
	async def get_user(self, user_id) -> User:
		return self.user_dict.get(user_id, None)
	
	async def heart_user(self, user_id):
		self.heart_set.add(user_id)
	
	async def check_heart(self):
		closeSet = set()
		for user_id in self.user_dict:
			if user_id in self.heart_set:
				continue
			closeSet.add(user_id)
		
		for user_id in closeSet:
			print("心跳超时",user_id)
			await misc.close_user(user_id)
		self.heart_set = set()
